<?php

$weixin_pay_config = config_item("weixin_pay");
// config.php
$config = [
    'appid' => $weixin_pay_config["appid"], // 小程序APPID
    'mchid' => $weixin_pay_config['mchid'], // 商户号
    'api_v3_key' => $weixin_pay_config['api_v3_key'], // APIv3密钥
    'serial_no' => $weixin_pay_config['api_serial_no'], // 商户证书序列号
    'private_key' => file_get_contents($weixin_pay_config["api_private_key"]), // 商户私钥
    'notify_url' => 'https://yourdomain.com/pay/notify.php', // 支付通知URL
    'wechatpay_public_key' => file_get_contents($weixin_pay_config["public_key"]) // 微信支付公钥
];

/**
 * 创建Native支付订单
 */
function createNativeOrder($description, $orderNo, $amount) {
    global $config;

    $url = 'https://api.mch.weixin.qq.com/v3/pay/transactions/native';
    $data = [
        'mchid' => $config['mchid'],
        'appid' => $config['appid'], // 使用小程序APPID
        'description' => $description,
        'out_trade_no' => $orderNo,
        'notify_url' => $config['notify_url'],
        'amount' => [
            'total' => intval($amount * 100), // 转换为分
            'currency' => 'CNY'
        ]
    ];

    $headers = generateRequestHeaders(json_encode($data), $url, 'POST');
    $response = httpRequest($url, json_encode($data), $headers);
    $result = json_decode($response, true);

    return $result['code_url'] ?? false;
}

/**
 * 生成带签名的请求头
 */
function generateRequestHeaders($body, $url, $method) {
    global $config;

    $timestamp = time();
    $nonceStr = bin2hex(random_bytes(16));
    $urlParts = parse_url($url);
    $canonicalUrl = ($urlParts['path'] ?? '/') . (isset($urlParts['query']) ? '?' . $urlParts['query'] : '');

    // 构造签名串
    $signatureStr = sprintf("%s\n%s\n%s\n%s\n%s\n",
            $method,
            $canonicalUrl,
            $timestamp,
            $nonceStr,
            $body
    );

    // 使用商户私钥签名
    openssl_sign($signatureStr, $signature, $config['private_key'], OPENSSL_ALGO_SHA256);
    $signatureBase64 = base64_encode($signature);

    // 生成Authorization头
    $auth = sprintf('WECHATPAY2-SHA256-RSA2048 mchid="%s",nonce_str="%s",signature="%s",timestamp="%d",serial_no="%s"',
            $config['mchid'],
            $nonceStr,
            $signatureBase64,
            $timestamp,
            $config['serial_no']
    );

    return [
        'Content-Type: application/json',
        'Accept: application/json',
        'Authorization: ' . $auth,
        'User-Agent: MyPayClient/1.0'
    ];
}

/**
 * 处理支付回调（使用微信支付公钥验证签名）
 */
function handlePaymentNotify() {
    global $config;

    // 获取回调数据
    $headers = getallheaders();
    $body = file_get_contents('php://input');

    // 验证签名
    $signature = $headers['Wechatpay-Signature'] ?? '';
    $timestamp = $headers['Wechatpay-Timestamp'] ?? '';
    $nonce = $headers['Wechatpay-Nonce'] ?? '';
    $serial = $headers['Wechatpay-Serial'] ?? '';

    // 构造签名串
    $signatureStr = "$timestamp\n$nonce\n$body";

    // 使用微信支付公钥验证签名
    $verified = openssl_verify(
            $signatureStr,
            base64_decode($signature),
            $config['wechatpay_public_key'],
            OPENSSL_ALGO_SHA256
    );

    if ($verified !== 1) {
        http_response_code(401);
        error_log("签名验证失败: " . openssl_error_string());
        exit('签名验证失败');
    }

    // 解密资源数据
    $data = json_decode($body, true);
    $resource = $data['resource'];
    $plaintext = openssl_decrypt(
            base64_decode($resource['ciphertext']),
            'aes-256-gcm',
            $config['api_v3_key'],
            OPENSSL_RAW_DATA,
            base64_decode($resource['nonce']),
            $resource['associated_data']
    );

    if (!$plaintext) {
        http_response_code(400);
        exit('数据解密失败');
    }

    $result = json_decode($plaintext, true);

    // 处理支付成功逻辑
    if ($result['trade_state'] === 'SUCCESS') {
        $orderId = $result['out_trade_no'];
        $transactionId = $result['transaction_id'];

        // TODO: 更新订单状态等业务逻辑
        file_put_contents('payment.log',
                date('[Y-m-d H:i:s] ') . "订单 {$orderId} 支付成功\n",
                FILE_APPEND
        );

        // 返回成功响应
        http_response_code(200);
        echo json_encode(['code' => 'SUCCESS', 'message' => '成功']);
    } else {
        http_response_code(200);
        echo json_encode(['code' => 'FAIL', 'message' => $result['trade_state_desc']]);
    }
}

/**
 * HTTP请求函数
 */
function httpRequest($url, $data = null, $headers = []) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);

    if ($data) {
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    }

    if ($headers) {
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    }

    $response = curl_exec($ch);

    if (curl_errno($ch)) {
        throw new Exception('Curl error: ' . curl_error($ch));
    }

    curl_close($ch);
    return $response;
}

// 主流程
if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['action'])) {
    switch ($_GET['action']) {
        case 'create':
            $product = $_GET['product'] ?? '测试商品';
            $orderId = 'ORDER_' . time() . '_' . mt_rand(1000, 9999);
            $amount = $_GET['amount'] ?? 0.01;

            $codeUrl = createNativeOrder($product, $orderId, $amount);
            if ($codeUrl) {
//                // 生成二维码
//                require 'vendor/autoload.php';
//                $qrCode = new \Endroid\QrCode\QrCode($codeUrl);
//                $qrCode->setSize(300);
//                header('Content-Type: ' . $qrCode->getContentType());
//                echo $qrCode->writeString();

                include "phpqrcode.php";

                $errorCorrectionLevel = 'L'; //容错级别
                $matrixPointSize = 6; //生成图片大小
                //生成二维码图片
                $type_id = 1;
                if ($type_id == 1) {
                    QRimage::$img_bg = [67, 140, 203];
                } else if ($type_id == 2) {
                    QRimage::$img_bg = [0, 166, 80];
                }

                $qrcode_image_url = PUBLIC_URL . "/qrcode/ddtodriver/?from_user_id=" . $from_user_id . "&from=driverCode";
                //echo $qrcode_image_url;
                $qrcode_image = QRcode::png($codeUrl, false, $errorCorrectionLevel, $matrixPointSize, 2);
                echo $qrcode_image;
            } else {
                echo "订单创建失败";
            }
            exit;
    }
}